package com.zq.it.action.admin;

import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.List;

import javax.annotation.Resource;

import com.zq.it.action.BaseAction;
import com.zq.it.pojo.Admin;
import com.zq.it.pojo.User;
import com.zq.it.service.admin.AdminService;
import com.zq.it.tool.Constant;

import net.sf.json.JSONArray;
public class AdminAction extends BaseAction {

	/**
	* 
	*/
	private static final long serialVersionUID = 1L;
	// 注入教师服务

	@Resource
	private AdminService adminService;
	// @Resource
	// private AdminService adminService;

	private List<Admin> list;
	private BigInteger userId;
	private String password;
	private String verify;

	public String getVerify() {
		return verify;
	}
	public void setVerify(String verify) {
		this.verify = verify;
	}

	public BigInteger getUserId() {
		return userId;
	}
	public void setUserId(BigInteger userId) {
		this.userId = userId;
	}

	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}

	public void validateLogin() {
		if (!getVerify().equals(
				getRequest().getSession().getAttribute(Constant.SECURITY_CODE)))
			addFieldError("verify", "验证码输入有误！");
		else {
			list = adminService.getAdmin(userId);
			if (list.size() > 0) {
				if (!list.get(0).getPassword().equals(getPassword()))
					addFieldError("password", "密码输入有误！");
			} else
				addFieldError("userId", "用户不存在！");
		}
	}

	/* 登录ajax */

	public String login() {

		Admin admin = list.get(0);
		if (admin != null) {
			admin.addCount();
			admin.setPretime(new Timestamp(System.currentTimeMillis()));
			adminService.renewalAdmin(admin);
			getHttpSession().setAttribute(Constant.ADMIN, admin);
			getHttpSession().setAttribute(Constant.USER, new User(admin.getId().toString()));
		}
		return "adminMain";
	}

	public String exit() {
		getHttpSession().removeAttribute(Constant.USER);
		getHttpSession().removeAttribute(Constant.ADMIN);
		return INPUT;
	}

	/**
	 * grant authority to teacher
	 * 
	 */
	public void grantAuto() {
		if (admin != null) {
			adminService.saveOrUpdateAdmin(admin);
		}

		print("<script>parent.closeWindow('已授权！');</script>", "UTF-8",
				"text/html");
	}

	public void deleteAdminById() {
		adminService.removeAdmin(bid);
		print("<script>parent.closeWindow('已删除权限！');</script>", "UTF-8",
				"text/html");
	}

	private Admin admin = null;

	public Admin getAdmin() {
		return admin;
	}
	public void setAdmin(Admin admin) {
		this.admin = admin;
	}

	public void searchAmdinById() {
		// System.out.println(id);
		if (bid != null)
			print(JSONArray.fromObject(adminService.getAdmin(bid)).toString(),
					"UTF-8", "TEXT/JSON");
	}

	private BigInteger bid = null;

	public BigInteger getBid() {
		return bid;
	}
	public void setBid(BigInteger bid) {
		this.bid = bid;
	}

}
